package com.lotso.web.module.organization.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lotso.web.common.ReqParam;
import com.lotso.web.common.exception.BusinessException;
import com.lotso.web.common.utils.UserUtil;
import com.lotso.web.module.organization.entity.Office;
import com.lotso.web.module.organization.mapper.IOfficeMapper;
import com.lotso.web.module.organization.service.IOfficeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName: OfficeServiceImpl
 * Description:
 * Date: 2018/9/27 18:47 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OfficeServiceImpl extends ServiceImpl<IOfficeMapper, Office> implements IOfficeService {

    @Autowired
    IOfficeMapper officeMapper;

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Office> list() {
        return officeMapper.selectList(new EntityWrapper<Office>().orderBy("sort", true));
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Office> list(ReqParam reqParam) {
        EntityWrapper<Office> wrapper = new EntityWrapper<>();
        wrapper.eq(reqParam.getSearchKey(), reqParam.getSearchValue());
        return officeMapper.selectList(wrapper.orderBy("sort", true));
    }

    @Override
    public boolean add(Office office) {
        return officeMapper.insert(office) > 0;
    }

    @Override
    public boolean update(Office office) {
        return officeMapper.updateById(office) > 0;
    }

    @Override
    public boolean delete(String officeId) {
        List<Office> children = officeMapper.selectList(new EntityWrapper<Office>().eq("parentId", officeId));
        if (children != null && children.size() > 0) {
            throw new BusinessException("该机构下有下级机构，请先删除下级机构");
        }
        return officeMapper.deleteById(officeId) > 0;
    }

    @Override
    public List<Office> authGet(String type) {
        String username = UserUtil.getPrincipalName();
        return officeMapper.authGet(username, type);
    }
}